<template>
  <div class="page">
    <div class="c-main p20">
      <div class="c-body">
        <el-row type="flex" justify="center">
          <el-col :span="24">
            <div class="clearfix">
              <div class="c-avatar">
                <img :src="pageAjax.data.avatarUrl" alt="" />
              </div>
              <div class="c-info">
                <el-form label-width="100px" class="form-condensed">
                  <div>
                    <el-form-item
                      label="昵称："
                      class="inlineBlock"
                      v-if="pageAjax.data.nickName"
                    >
                      {{ pageAjax.data.nickName || "无" }}
                    </el-form-item>
                    <el-form-item
                      label="姓名："
                      class="inlineBlock"
                      v-if="pageAjax.data.realName"
                    >
                      {{ pageAjax.data.realName || "无" }}
                    </el-form-item>
                    <el-form-item label="性别：" class="inlineBlock">
                      {{ pageAjax.data.gender == 1 ? "男" : "女" }}
                    </el-form-item>
                    <el-form-item
                      v-if="pageAjax.data.signStatus"
                      label="签约状态："
                      class="inlineBlock"
                    >
                      {{ translate.STATUS[pageAjax.data.signStatus] || "无" }}
                    </el-form-item>
                    <el-form-item label="是否签约：" class="inlineBlock">
                      {{ pageAjax.data.hasSign ? "已签约" : "没有签约" }}
                    </el-form-item>
                    <el-form-item
                      v-if="pageAjax.data.signType"
                      label="签约类型："
                      class="inlineBlock"
                    >
                      {{ pageAjax.data.signType || "无" }}
                    </el-form-item>
                    <el-form-item
                      v-if="pageAjax.data.hasContract"
                      label="全部合同是否保留："
                      class="inlineBlock"
                    >
                      {{
                        (pageAjax.data.hasContract === true ? "是" : "否") ||
                          "无"
                      }}
                    </el-form-item>
                    <el-form-item
                      label="合约期限："
                      class="inlineBlock"
                      v-if="pageAjax.data.signPeriod"
                    >
                      {{ pageAjax.data.signPeriod || "无" }}
                    </el-form-item>
                  </div>
                  <div>
                    <el-form-item
                      v-if="pageAjax.data.operator"
                      label="现属运营："
                      class="inlineBlock"
                    >
                      {{
                        pageAjax.data.operator.corporationName +
                          "-" +
                          pageAjax.data.operator.departmentName +
                          "-" +
                          pageAjax.data.operator.nickName || "无"
                      }}
                    </el-form-item>
                  </div>
                  <div
                    v-if="
                      pageAjax.data.profitCost &&
                        pageAjax.data.profitCost.totalCost
                    "
                  >
                    <el-form-item
                      label="截止至昨天总成本："
                      class="inlineBlock"
                    >
                      {{ pageAjax.data.profitCost.totalCost || "无" }}
                    </el-form-item>
                  </div>
                </el-form>
              </div>
            </div>
          </el-col>
        </el-row>
        <div class="mt10"></div>
        <el-divider></el-divider>
        <el-row
          type="flex"
          justify="center"
          v-show="!pageAjax.data.liveRooms || !pageAjax.data.liveRooms.length"
        >
          <el-col :span="24">
            <div class="c-tip tc">
              暂无直播信息，请
              <el-button size="mini" @click="rTriggerCreateLive"
                >添加直播间信息</el-button
              >
              绑定读取直播数据
            </div>
          </el-col>
        </el-row>

        <el-row
          type="flex"
          justify="center"
          v-show="pageAjax.data.liveRooms && pageAjax.data.liveRooms.length"
        >
          <el-col :span="24">
            <div class="clearfix">
              <el-button
                type="primary"
                class="fr btn"
                size="mini"
                @click="rTriggerCreateLive"
                v-hasAuth:seestar_addLive
                >添加直播间信息</el-button
              >
            </div>
            <div class="c-tabs mt20">
              <el-tabs
                type="card"
                closable
                v-model="alone.currentTabId"
                @tab-remove="rDeleteLive"
              >
                <el-tab-pane
                  v-for="(item, index) in pageAjax.data.liveRooms"
                  :key="item.id"
                  :label="
                    '直播间 ' +
                      (index + 1) +
                      '(' +
                      transletePlatform(item.platform) +
                      ')'
                  "
                  :name="'' + item.id"
                >
                  <div>
                    <el-form label-width="100px" class="form-condensed">
                      <el-form-item
                        label="直播平台："
                        class="inlineBlock"
                        v-if="item.platform"
                      >
                        {{ transletePlatform(item.platform) || "无" }}
                      </el-form-item>
                      <el-form-item
                        label="直播id："
                        class="inlineBlock"
                        v-if="item.anchorNo"
                      >
                        {{ item.anchorNo || "无" }}
                      </el-form-item>
                      <el-form-item class="inlineBlock">
                        <el-button
                          size="small"
                          v-hasAuth:seestar_editLive
                          @click="rTriggerEditLive(index)"
                          >编辑直播间信息</el-button
                        >
                      </el-form-item>
                    </el-form>
                  </div>
                  <div>
                    <el-form label-width="120px">
                      <el-form-item
                        label="直播分成比例："
                        class="inlineBlock"
                        v-if="
                          item.ratioPlatform ||
                            item.ratioAnchor ||
                            item.ratioGuild
                        "
                      >
                        平台分成：{{ item.ratioPlatform + "%" || "无" }}，
                        主播分成：{{ item.ratioAnchor + "%" || "无" }}，
                        公会分成：{{ item.ratioGuild + "%" || "无" }}
                      </el-form-item>
                      <el-form-item
                        label="截止昨天总流水："
                        class="inlineBlock"
                        v-if="item.profitCost && item.profitCost.totalStream"
                      >
                        {{ item.profitCost.totalStream || "无" }}
                      </el-form-item>
                      <el-form-item
                        label="截止昨天公会总收益："
                        class="inlineBlock"
                        v-if="
                          item.profitCost && item.profitCost.totalGuildRevenue
                        "
                      >
                        {{ item.profitCost.totalGuildRevenue || "无" }}
                      </el-form-item>
                    </el-form>
                  </div>
                  <div v-if="hasAuth(['seestar_liveTurnover'])">
                    <el-divider></el-divider>
                    <el-form label-width="150px" inline="">
                      <el-form-item label="主播直播流水曲线图">
                        <el-date-picker
                          v-model="alone.searchTurnoverForm.data.dateTime"
                          type="datetimerange"
                          range-separator="至"
                          start-placeholder="请选择创建开始时间"
                          end-placeholder="请选择创建结束时间"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          :unlink-panels="true"
                        ></el-date-picker>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="default" @click="rSearchTurnover"
                          >查询</el-button
                        >
                      </el-form-item>
                    </el-form>
                    <el-row
                      type="flex"
                      justify="center"
                      v-show="
                        pageAjax.data.liveRooms &&
                          pageAjax.data.liveRooms.length
                      "
                    >
                      <el-col :span="10">
                        <div
                          class="c-chart"
                          v-show="
                            actorTurnoverSupAjax.data &&
                              actorTurnoverSupAjax.data.length
                          "
                        >
                          <div class="c-turnoverBox">
                            <div
                              class="c-turnover full"
                              :id="'turnoverref' + item.id"
                            ></div>
                          </div>
                        </div>
                      </el-col>
                    </el-row>
                    <el-row
                      type="flex"
                      justify="center"
                      v-show="
                        actorTurnoverSupAjax.data &&
                          actorTurnoverSupAjax.data.length
                      "
                    >
                      <el-col :span="15">
                        <el-table
                          stripe
                          :data="actorTurnoverSupAjax.data"
                          style="width: 100%"
                          max-height="350"
                        >
                          <el-table-column label="日期" width="180">
                            <template slot-scope="scope">
                              <div class="">
                                {{ scope.row.dt || "无" }}
                              </div>
                            </template>
                          </el-table-column>
                          <el-table-column label="流水(元)" width="180">
                            <template slot-scope="scope">
                              <div class="">
                                {{ scope.row.revenue || 0 }}
                              </div>
                            </template>
                          </el-table-column>
                          <el-table-column label="流水(上周同期)">
                            <template slot-scope="scope">
                              <div class="">
                                {{ scope.row.revenue_lastweek || 0 }}
                              </div>
                            </template>
                          </el-table-column>
                          <el-table-column label="流水(上月同期)">
                            <template slot-scope="scope">
                              <div class="">
                                {{ scope.row.revenue_lastmonth || 0 }}
                              </div>
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </el-row>
                    <div
                      class="tc"
                      v-show="
                        !actorTurnoverSupAjax.data ||
                          !actorTurnoverSupAjax.data.length
                      "
                    >
                      没有任何数据
                    </div>
                  </div>
                  <div v-else class="tc">您没有权限查看该主播流水</div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- liveDrawerCp -->
    <el-drawer
      :title="liveDrawerCp.config.title"
      :visible.sync="liveDrawerCp.config.visible"
      :direction="liveDrawerCp.config.direction"
      :size="liveDrawerCp.config.size"
    >
      <div class="f-liveDrawerCp">
        <div class="n-content">
          <el-row>
            <el-col :span="8" :offset="8">
              <el-form ref="status" label-width="150px">
                <el-form-item label="*选择直播平台：">
                  <el-select
                    v-model="liveDrawerCp.data.platform"
                    placeholder="选择直播平台"
                  >
                    <el-option
                      v-for="item in biPlatformListSupAjax.data"
                      :key="item.value"
                      :label="item.name"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="*主播号：">
                  <el-input
                    placeholder="主播号"
                    v-model="liveDrawerCp.data.anchorNo"
                  ></el-input>
                </el-form-item>
                <div style="margin-top: -19px;">
                  <el-row>
                    <el-col :span="22">
                      <el-form-item label="平台分成：">
                        <el-input
                          placeholder="平台分成"
                          v-model="liveDrawerCp.data.ratioPlatform"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="2"
                      ><el-button type="text" disabled=""
                        >&nbsp;&nbsp;%</el-button
                      ></el-col
                    >
                  </el-row>
                  <el-row>
                    <el-col :span="22">
                      <el-form-item label="主播分成：">
                        <el-input
                          placeholder="主播分成"
                          v-model="liveDrawerCp.data.ratioAnchor"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="2"
                      ><el-button type="text" disabled=""
                        >&nbsp;&nbsp;%</el-button
                      ></el-col
                    >
                  </el-row>
                  <el-row>
                    <el-col :span="22">
                      <el-form-item label="公会：">
                        <el-input
                          placeholder="公会"
                          v-model="liveDrawerCp.data.ratioGuild"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="2"
                      ><el-button type="text" disabled=""
                        >&nbsp;&nbsp;%</el-button
                      ></el-col
                    >
                  </el-row>
                </div>
                <el-form-item>
                  <el-button type="primary" @click="rSubmitCreateForm"
                    >提交</el-button
                  >
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {
  getLiveActorInfo,
  addLive,
  deleteLive,
  getActorTurnover
} from "@/api/actor.js";
import { getGivenDate } from "@/assets/js/util.js";
import { getBiPlatformList } from "@/api/others.js";
import _ from "lodash";
export default {
  name: "seestar_liveDetail",
  data: () => ({
    pageAjax: {
      loading: false,
      data: {}
    },
    biPlatformListSupAjax: {
      data: []
    },
    actorTurnoverSupAjax: {
      loading: false,
      data: []
    },

    alone: {
      currentTabId: "",
      actorTurnoverLoading: null,
      searchTurnoverForm: {
        data: { dateTime: "" }
      },
      turnoverChartFn: {},
      turnoverChart: {
        oTurnoverChart: {},
        option: {
          title: {
            text: ""
          },
          tooltip: {},
          legend: {
            icon: "stack",
            data: ["流水(元)", "流水(上周同期)", "流水(上月同期)"]
          },
          xAxis: {
            type: "category",
            data: []
          },
          yAxis: {},
          series: [
            {
              name: "流水(元)",
              type: "bar",
              data: []
            },
            {
              name: "流水(上周同期)",
              type: "bar",
              data: []
            },
            {
              name: "流水(上月同期)",
              type: "bar",
              data: []
            }
          ]
        }
      }
    },
    translate: {
      STATUS: {}
    },

    liveDrawerCp: {
      loading: false,
      config: {
        title: "",
        visible: false,
        direction: "ttb",
        size: "70%"
      },
      data: {
        platform: "",
        anchorNo: "",
        onlineType: "",
        ratioAnchor: "",
        ratioGuild: "",
        ratioPlatform: ""
      }
    }
  }),
  watch: {
    "alone.currentTabId"() {
      // if (this.alone.currentTabId != 0) {
      //   this.alone.actorTurnoverLoading = this.$loading();
      //   this.actorTurnoverSupAjax.data = [];
      //   this.renderTurnOverChart();
      // }
    },
    "pageAjax.data"() {
      let _that = this;
      if (
        _that.pageAjax.data.liveRooms &&
        _that.pageAjax.data.liveRooms.length
      ) {
        _that.alone.currentTabId = _that.pageAjax.data.liveRooms[0].id + "";
      }
    }
  },
  created() {
    let _that = this;
    _that.translate.STATUS = this.SIGN.STATUS.translate;
    _that.alone.searchTurnoverForm.data.dateTime = [
      getGivenDate(-7),
      getGivenDate(0)
    ];

    _that.getBiPlatformListData();
  },
  mounted() {
    let _that = this;

    _that.getPageData();
  },
  destroyed() {
    let _that = this;
    let turnoverChartFnKeys = Object.keys(_that.alone.turnoverChartFn) || [];
    turnoverChartFnKeys.forEach(item => {
      window.removeEventListener("resize", _that.alone.turnoverChartFn[item]);
    });
  },
  methods: {
    rTriggerCreateLive() {
      let _that = this;

      if (!_that.hasAuth(["seestar_addLive"])) {
        _that.$message.error("你没有权限增加，请联系管理员增加权限");
        return;
      }

      _that.liveDrawerCp.config.visible = true;
      _that.liveDrawerCp.data = {
        platform: "",
        anchorNo: "",
        onlineType: "",
        ratioAnchor: "",
        ratioGuild: "",
        ratioPlatform: ""
      };
    },
    rTriggerEditLive(index) {
      let _that = this;
      _that.liveDrawerCp.data = {
        anchorId: _that.$route.query.anchorId,
        id: _that.pageAjax.data.liveRooms[index].id,
        platform: _that.pageAjax.data.liveRooms[index].platform,
        anchorNo: _that.pageAjax.data.liveRooms[index].anchorNo,
        onlineType: _that.pageAjax.data.liveRooms[index].onlineType,
        ratioAnchor: _that.pageAjax.data.liveRooms[index].ratioAnchor,
        ratioGuild: _that.pageAjax.data.liveRooms[index].ratioGuild,
        ratioPlatform: _that.pageAjax.data.liveRooms[index].ratioPlatform
      };
      _that.liveDrawerCp.config.visible = true;
    },
    rDeleteLive(id) {
      let _that = this;
      if (!_that.hasAuth(["seestar_deleteLive"])) {
        _that.$message.error("你没有权限删除，请联系管理员增加权限");
        return;
      }

      this.$confirm("你确定要删除此直播间?", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteLive({ id: id }).then(resp => {
            let respData = resp.data || {};

            if (respData.code === _that.STATUS.success[0]) {
              _that.$message.success(respData.msg || "删除成功");
              _that.getPageData();
            } else {
              _that.$message.error(respData.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    rSubmitCreateForm() {
      let _that = this;
      let liveDrawerCpData = _that.liveDrawerCp.data;
      if (_that.liveDrawerCp.loading) {
        return;
      }

      if (!liveDrawerCpData.platform) {
        _that.$message.error("请选择直播平台");
        return;
      }
      if (!liveDrawerCpData.anchorNo) {
        _that.$message.error("主播号不能为空");
        return;
      }
      if (
        liveDrawerCpData.ratioPlatform &&
        isNaN(liveDrawerCpData.ratioPlatform)
      ) {
        _that.$message.error("平台分成比例必须为数字");
        return;
      }
      if (liveDrawerCpData.ratioAnchor && isNaN(liveDrawerCpData.ratioAnchor)) {
        _that.$message.error("主播分成比例必须为数字");
        return;
      }

      if (liveDrawerCpData.ratioGuild && isNaN(liveDrawerCpData.ratioGuild)) {
        _that.$message.error("公会分成比例必须为数字");
        return;
      }
      _that.liveDrawerCp.loading = true;
      liveDrawerCpData.anchorId = _that.$route.query.anchorId;
      addLive(liveDrawerCpData)
        .then(resp => {
          let respData = resp.data;
          if (respData.code === _that.STATUS.success[0]) {
            _that.$message.success(respData.msg);
            _that.liveDrawerCp.config.visible = false;
            _that.getPageData();
          } else {
            _that.$message.error(respData.msg);
          }
        })
        .finally(() => {
          _that.liveDrawerCp.loading = false;
        });
    },
    rSearchTurnover() {
      let _that = this;
      if (
        !_that.alone.searchTurnoverForm.data.dateTime ||
        !_that.alone.searchTurnoverForm.data.dateTime.length
      ) {
        _that.$message.error("请选择要查询的日期");
        return;
      }
      _that.alone.actorTurnoverLoading = this.$loading();
      _that.getActorTurnover();
    },
    renderTurnOverChart: _.debounce(function() {
      let _that = this;
      let liveRooms = _that.pageAjax.data.liveRooms || [];
      if (!liveRooms.length) {
        return;
      }
      let currentTabId = _that.alone.currentTabId;
      if (!_that.alone.turnoverChart.oTurnoverChart[currentTabId]) {
        let turnoverChartRef = document.getElementById(
          "turnoverref" + currentTabId
        );
        _that.alone.turnoverChart.oTurnoverChart[
          currentTabId
        ] = _that.$echarts.init(turnoverChartRef);
        _that.alone.turnoverChartFn[currentTabId] = function() {
          _that.alone.turnoverChart.oTurnoverChart[currentTabId].resize();
        };

        window.addEventListener(
          "resize",
          _that.alone.turnoverChartFn[currentTabId]
        );
      }

      _that.getActorTurnover();
    }, 800),
    getPageData() {
      let _that = this;
      return getLiveActorInfo({
        params: { anchorId: _that.$route.query.anchorId }
      })
        .then(resp => {
          let respData = resp.data || {};

          if (respData.code === _that.STATUS.success[0]) {
            _that.pageAjax.data = respData.data;
          } else {
            _that.$message.error(respData.msg || "获取失败");
          }
        })
        .finally(() => {});
    },
    getBiPlatformListData() {
      let _that = this;
      return getBiPlatformList()
        .then(resp => {
          let respData = resp.data || {};

          if (respData.code === _that.STATUS.success[0]) {
            let arr = respData.data.filter(item => {
              if (item.value != "all") {
                return item;
              }
            });
            _that.biPlatformListSupAjax.data = arr;
          } else {
            _that.$message.error(respData.msg || "获取失败");
          }
        })
        .finally(() => {});
    },
    getActorTurnover() {
      let _that = this;

      if (_that.actorTurnoverSupAjax.loading) {
        _that.$message.error("数据请求中，请稍等");
        return;
      }
      let pageData = _that.pageAjax.data;
      let currentTabId = _that.alone.currentTabId;
      let currentLiveRooms;
      if (!pageData.liveRooms || !pageData.liveRooms.length) {
        return;
      }
      pageData.liveRooms.forEach(item => {
        if (currentTabId == item.id) {
          currentLiveRooms = item;
          return;
        }
      });

      _that.actorTurnoverSupAjax.loading = true;

      getActorTurnover({
        params: {
          anchorNo: currentLiveRooms.anchorNo,
          // anchorNo: 514737281,
          platform: currentLiveRooms.platform,
          // platform: "bilibili",
          startDate: _that.alone.searchTurnoverForm.data.dateTime[0],
          endDate: _that.alone.searchTurnoverForm.data.dateTime[1]
        }
      })
        .then(resp => {
          let respData = resp.data || {};

          if (respData.code === _that.STATUS.success[0]) {
            respData.data = respData.data || [];
            _that.actorTurnoverSupAjax.data = respData.data;
            let currentTurnover = [];
            let lastWeekTurnover = [];
            let lastMonthTurnover = [];
            let days = [];
            respData.data.forEach(item => {
              currentTurnover.push(item.revenue || 0);
              lastWeekTurnover.push(item.revenue_lastweek || 0);
              lastMonthTurnover.push(item.revenue_lastmonth || 0);
              days.push(item.dt);
            });

            _that.alone.turnoverChart.option.series = [
              {
                name: "流水(元)",
                type: "line",
                data: currentTurnover
              },
              {
                name: "流水(上周同期)",
                type: "line",
                data: lastWeekTurnover
              },
              {
                name: "流水(上月同期)",
                type: "line",
                data: lastMonthTurnover
              }
            ];
            _that.alone.turnoverChart.option.xAxis.data = days;

            _that.alone.turnoverChart.oTurnoverChart[currentTabId].setOption(
              _that.alone.turnoverChart.option
            );
            setTimeout(() => {
              _that.alone.turnoverChart.oTurnoverChart[currentTabId].resize();
            }, 500);
          } else {
            _that.$message.error(respData.msg || "获取失败");
          }
        })
        .finally(() => {
          _that.actorTurnoverSupAjax.loading = false;
          _that.alone.actorTurnoverLoading.close();
        });
    },
    transletePlatform(value) {
      let str = "";

      this.biPlatformListSupAjax.data.forEach(item => {
        if (item.value == value) {
          str = item.name;
          return;
        }
      });

      return str;
    }
  }
};
</script>
<style lang="scss">
.page {
  .c-body {
    .block {
      display: block;
    }
    .inlineBlock {
      display: inline-block;
    }
    .c-avatar {
      float: left;
      width: 80px;
      height: 80px;
      box-shadow: 0 0 0 5px #eee;
      border-radius: 50%;
      overflow: hidden;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .c-info {
      margin-left: 100px;
    }
    .c-tip {
      margin: 100px 0;
    }
  }
  .c-chart {
    width: 100%;
    padding-top: 100%;
    position: relative;
  }
  .c-turnoverBox {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
  }
  .f-liveDrawerCp {
    overflow: hidden;
    position: absolute;
    width: 100%;
    left: 0;
    top: 50px;
    bottom: 0;
    .n-content {
      height: 100%;
      padding: 30px 0;
      overflow: auto;
      box-sizing: border-box;
    }
    .n-note {
      line-height: 2;
      color: #999;
    }
    .n-compact {
      border-top: 1px solid #eee;
    }
  }
}
</style>
